from django.shortcuts import render

# Create your views here.
from django.http import HttpResponse, JsonResponse, FileResponse
from django.views.decorators.csrf import csrf_exempt
from rest_framework.parsers import JSONParser
#from snippets.models import Snippet
#from snippets.serializers import SnippetSerializer
from rest_framework.decorators import api_view
from rest_framework.response import Response
from django.db.models import F,Q

#from snippets.models import Snippet
from snippets.models import BlockInfo, ExtrinsicsInfo, EventInfo, TransactionInfo
from django.db import connection
#from snippets.serializers import SnippetSerializer
#from snippets.serializers import ProjectTypeSerializer, ProjectAbstructSerializer
from rest_framework import generics
from urllib import request as Request
import os
import json
import time
import hashlib
"""
获取最新的block信息
"""
@api_view(['GET'])
def get_newest_block_info(request):
    if request.method == 'GET':
        rtn = []
        sql = """
        SELECT 
            time, number, extrinsics_count, transaction_count
        FROM 
            BlockInfoLatest
        order by time desc
        limit 0,10;
        """
        with connection.cursor() as cursor:
            cursor.execute(sql)
            rows = cursor.fetchall()
            for item in rows:
                rtn.append({
                    "time": time.strftime("%Y-%m-%d %H:%M:%S", time.localtime(item[0]/1000)),
                    "number": item[1],
                    "extrinsics_count": item[2],
                    "transaction_count":item[3]
                })
        return Response(rtn)

@api_view(['GET'])
def get_newest_transaction_info(request):
    if request.method == 'GET':
        rtn = []
        sql = """
        select 
            src, 
            dest,
            amount,
            hash
        from
            TransactionInfoLatest
        order by TransactionInfoLatest.time desc
        limit 0, 10
        """
        with connection.cursor() as cursor:
            cursor.execute(sql)
            rows = cursor.fetchall()
            for item in rows:
                rtn.append({
                    "from": item[0],
                    "to": item[1],
                    "amount": item[2],
                    "hash":item[3]
                })
        return Response(rtn)



@api_view(['GET'])
def get_block_info_by_idx(request, param):
    if request.method == 'GET':
        info = BlockInfo.objects.filter(number = param).values_list("id", "number", "hash", "parentHash", "stateRoot", "extrinsicsRoot", "authorId", "finalized", "time").first()
        rtn = {
            "id": info[0], 
            "number": info[1], 
            "hash": info[2], 
            "parentHash": info[3], 
            "stateRoot": info[4], 
            "extrinsicsRoot": info[5], 
            "authorId": info[6], 
            "finalized": info[7], 
            "time": info[8]
        }
        return Response(rtn)

@api_view(['GET'])
def get_block_info_by_hash(request, param):
    if request.method == 'GET':
        info = BlockInfo.objects.filter(hash = param).values_list("id", "number", "hash", "parentHash", "stateRoot", "extrinsicsRoot", "authorId", "finalized", "time").first()
        rtn = {
            "id": info[0], 
            "number": info[1], 
            "hash": info[2], 
            "parentHash": info[3], 
            "stateRoot": info[4], 
            "extrinsicsRoot": info[5], 
            "authorId": info[6], 
            "finalized": info[7], 
            "time": info[8]
        }
        return Response(rtn)

@api_view(['GET'])
def get_transaction(request, hash):
    if request.method == 'GET':
        info = TransactionInfo.objects.filter(hash = hash).values_list("id", "number", "hash", "parentHash", "stateRoot", "extrinsicsRoot", "authorId", "finalized", "time").first()
        rtn = {
            "id": info[0], 
            "number": info[1], 
            "hash": info[2], 
            "parentHash": info[3], 
            "stateRoot": info[4], 
            "extrinsicsRoot": info[5], 
            "authorId": info[6], 
            "finalized": info[7], 
            "time": info[8]
        }
        return Response(rtn)


@api_view(['GET'])
def get_extrinsics(request, hash):
    if request.method == 'GET':
        if hash.find("'") != -1:
            return HttpResponse(status = 404)
        sql = """
        select 
            pallet,
            method,
            signature,
            nonce,
            args,
            ExtrinsicsInfo.`hash`,
            partialFee,
            success,
            block_id,
            signer,
            BlockInfo.number as block_number,
            BlockInfo.hash as block_hash,
            BlockInfo.time as time
        from 
            ExtrinsicsInfo,
            BlockInfo
        where
            ExtrinsicsInfo.block_id = BlockInfo.id and
            ExtrinsicsInfo.`hash` = '%s'
        limit 0,1
        """%hash
        with connection.cursor() as cursor:
            cursor.execute(sql)
            row = cursor.fetchall()[0]
            rtn = {
                "pallet": row[0],
                "method": row[1],
                "signature": row[2],
                "nonce": row[3],
                "args": row[4],
                "hash": row[5],
                "partialFee": row[6],
                "success": row[7],
                "block_id": row[8],
                "signer": row[9],
                "block_number": row[10],
                "block_hash": row[11],
                "time": row[12]
            }
            return Response(rtn)

@api_view(['GET'])
def get_extrinsics_by_id(request, hash, id):
    if request.method == 'GET':
        if hash.find("'") != -1:
            return HttpResponse(status = 404)
        sql = """
        select 
            pallet,
            method,
            signature,
            nonce,
            args,
            ExtrinsicsInfo.`hash`,
            partialFee,
            success,
            block_id,
            signer,
            BlockInfo.number as block_number,
            BlockInfo.hash as block_hash,
            BlockInfo.time as time
        from 
            ExtrinsicsInfo,
            BlockInfo
        where
            ExtrinsicsInfo.block_id = BlockInfo.id and
            ExtrinsicsInfo.`hash` = '%s' and
            ExtrinsicsInfo.`id` = %d
        limit 0,1
        """%(hash, id)
        with connection.cursor() as cursor:
            cursor.execute(sql)
            row = cursor.fetchall()[0]
            rtn = {
                "pallet": row[0],
                "method": row[1],
                "signature": row[2],
                "nonce": row[3],
                "args": row[4],
                "hash": row[5],
                "partialFee": row[6],
                "success": row[7],
                "block_id": row[8],
                "signer": row[9],
                "block_number": row[10],
                "block_hash": row[11],
                "time": row[12]
            }
            return Response(rtn)


@api_view(['GET'])
def get_latest_nft(request, nft_type):
    if request.method == 'GET':
        res = Request.urlopen('http://scanner_nodejs:3000/latest_nft/%d'%(nft_type), timeout = 20)
        html = res.read()
        json_obj = json.loads(html)
        return JsonResponse({
            "status": 0,
            "data":json_obj
        })

@api_view(['GET'])
def get_extrinsics_by_block_number(request, block_num):
    if request.method == 'GET':
        block_info = BlockInfo.objects.filter(number=block_num).first()
        info = ExtrinsicsInfo.objects.filter(block=block_info).values_list("id", "hash", "pallet", "method", "partialFee")
        rtn = []
        for item in info:
            rtn.append({
                "id": item[0], 
                "hash": item[1], 
                "pallet": item[2], 
                "method": item[3], 
                "fee": item[4]
            })
        return Response(rtn)


@api_view(['GET'])
def get_transaction_by_address(request, address, page_size, page_index):
    if request.method == 'GET':
        if address.find("'") != -1:
            return HttpResponse(status = 404)
        sql = """
            select 
                count(*)
            from 
                TransactionInfo,
                ExtrinsicsInfo,
                BlockInfo
            where 
                (src = '%s' or
                dest = '%s')and
                ExtrinsicsInfo.id = TransactionInfo.extrinsics_id and
                ExtrinsicsInfo.block_id = BlockInfo.id
        """%(address, address)
        count = 0
        rtn = {}
        with connection.cursor() as cursor:
            cursor.execute(sql)
            count = cursor.fetchall()[0][0]
            rtn["count"] = count

        sql = """
            select 
                ExtrinsicsInfo.hash as tx_hash,
                BlockInfo.hash as block_hash,
                ExtrinsicsInfo.time as `time`,
                TransactionInfo.src as `from`,
                TransactionInfo.dest as `to`,
                TransactionInfo.amount as `amount`,
                ExtrinsicsInfo.success as `result`
            from 
                TransactionInfo,
                ExtrinsicsInfo,
                BlockInfo
            where 
                (src = '%s' or
                dest = '%s')and
                ExtrinsicsInfo.id = TransactionInfo.extrinsics_id and
                ExtrinsicsInfo.block_id = BlockInfo.id
                order by `time` desc
                limit %d, %d;
        """%(address, address, page_size*(page_index-1), page_size)
        with connection.cursor() as cursor:
            cursor.execute(sql)
            rows = cursor.fetchall()
            rtn["data"] = []
            for item in rows:
                rtn["data"].append({
                    "tx_hash": item[0],
                    "block_hash": item[1],
                    "time": item[2],
                    "from": item[3],
                    "to": item[4],
                    "amount": item[5],
                    "result": item[6]
                })
            return Response(rtn)

@api_view(['GET'])
def get_address_info(request, address):
    if request.method == 'GET':
        res = Request.urlopen('http://scanner_sidecar:8080/accounts/%s/balance-info'%address, timeout = 20)
        html = res.read()
        json_obj = json.loads(html)
        return Response({
            "nonce":json_obj["nonce"],
            "free": json_obj["free"],
            "feeFrozen": json_obj["feeFrozen"]
        })